import * as echarts from "echarts"
import { useMemo, useRef, useEffect } from "react"

const Organization = ({ className, data = {} }) => {
  const chartRef = useRef(null)
  console.log(data)
  const { departments = [] } = data

  // prettier-ignore
  // let data = [12, 9, 15, 6];
  // let yMax = 20;
  // let dataShadow = [];
  // for (let i = 0; i < data.length; i++) {
  //   dataShadow.push(yMax);
  // }
  const option = useMemo(() => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '20%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: departments.map(item => item.name), //['部门一', '部门二', '部门三', '部门四'],
        axisTick: {
          alignWithLabel: true,
          show: false,
        }
      }
    ],
    yAxis: [
      {
        label: {
          show: true,
          textStyle: {
            color: '#999'
          }
        },
        name: '数量', // Y轴名称
        nameLocation: 'end',
          type: 'value'
        }
      ],
    series: [
      {
        name: 'Direct',
        type: 'bar',
        barWidth: '24%',
        data: departments.map(item => item.employees),
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,  // 从左开始
            y: 0,  // 从下开始
            x2: 0, // 到右结束
            y2: 1, // 到上结束
            colorStops: [{
              offset: 0, color: 'rgba(0, 200, 255, 1)' // 起始颜色
            }, {
              offset: 1, color: 'rgba(58, 77, 233, 1)' // 结束颜色
            }]
          }
        }
      }
    ]
  }), [departments])

  const myChart = useRef(null)
  useEffect(() => {
    if (chartRef.current) {
      if (!myChart.current) {
        myChart.current = echarts.init(chartRef.current)
      }
      myChart.current.setOption(option)
    }
  }, [option])

  return (
    <div className={className}>
      <h3 className="text-lg font-bold">组织架构</h3>
      <div id="org-chart" ref={chartRef} className="w-full h-[180px]"></div>
    </div>
  )
}

export default Organization
